package com.nfit.web.user;

import com.nfit.entity.User;
import com.nfit.entity.vo.ResponeVo;
import com.nfit.service.UserService;
import com.nfit.util.EmailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.nfit.entity.vo.ResponeVo.fail;
import static com.nfit.entity.vo.ResponeVo.success;

@RestController
public class UserController {
    @Autowired
    private UserService service;
    @Autowired
    private EmailUtils emailService;


    @RequestMapping("/login")
    public ResponeVo login(@RequestBody User user) {
        User login = service.login(user);
        if (login != null) {
            return success(login);
        }
        return fail("用户名或密码错误");
    }

    @RequestMapping("/register")
    public ResponeVo register(@RequestBody User user) {
        if (service.register(user)) {
            return success("注册成功");
        }
        return fail("用户已存在");
    }

    @RequestMapping("/sendCode")
    public ResponeVo sendCode(String email) {
        String code = emailService.sendEmailWithCode(email);
        return success(code);
    }

    @RequestMapping("user/UserInfo")
    public ResponeVo UserInfo(String userId) {
        User user = service.selectUserById(userId);
        if (user != null){
            return success(user);
        }
        return fail("用户不存在");
    }

    @RequestMapping("user/UpdateUserInfo")
    public ResponeVo UpdateUserInfo(@RequestBody User user) {
        int result = service.updateUserInfo(user);
        if (result == 1) {
            return success(user);
        }
        return fail("更新失败");
    }
}
